package com.jsz.peini.service.seller;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.jsz.peini.bean.order.OrderInfo;
import com.jsz.peini.bean.order.OrderSeller;
import com.jsz.peini.bean.order.OrderSellerExample;
import com.jsz.peini.bean.seller.SellerInfo;
import com.jsz.peini.bean.seller.SellerJudge;
import com.jsz.peini.bean.seller.SellerJudgeExample;
import com.jsz.peini.bean.task.TaskInfo;
import com.jsz.peini.bean.user.UserInfo;
import com.jsz.peini.bean.user.UserJudge;
import com.jsz.peini.common.constants.Constants;
import com.jsz.peini.common.util.AppPush;
import com.jsz.peini.common.util.PeiniUtils;
import com.jsz.peini.common.util.SmsSendUtil;
import com.jsz.peini.mapper.order.OrderInfoMapper;
import com.jsz.peini.mapper.order.OrderSellerMapper;
import com.jsz.peini.mapper.seller.SellerJudgeMapper;
import com.jsz.peini.mapper.task.TaskInfoMapper;
import com.jsz.peini.mapper.user.UserInfoMapper;
import com.jsz.peini.mapper.user.UserSmsMapper;
import com.jsz.peini.service.order.OrderInfoService;
import com.jsz.peini.service.user.UserInfoService;
import com.jsz.peini.service.user.UserJudgeService;

@Service
public class SellerJudgeService {
	private static final Logger logger = LoggerFactory.getLogger(SellerJudgeService.class);
	@Resource
	private SellerJudgeMapper sellerJudgeMapper;
	
	@Resource
	private OrderInfoMapper orderInfoMapper;
	
	@Resource
	private UserSmsMapper userSmsMapper;
	
	@Resource
	private OrderSellerMapper orderSellerMapper;
	
	@Resource
	private TaskInfoMapper taskInfoMapper;
	
	@Resource
	private UserInfoMapper userInfoMapper;
	
	@Autowired
	private SellerInfoService sellerInfoService;
	
	@Autowired
	private UserJudgeService userJudgeService;
	
	@Autowired
	private UserInfoService userInfoService;
	
	@Autowired
	private OrderInfoService orderInfoService;
	
	
	public int insertJudge(SellerJudge sellerJudge){
		int result = sellerJudgeMapper.insert(sellerJudge);
		return result;
	}
	
	@Transactional
	public Object sellerJudge(SellerJudge sellerJudge, Long orderId,String userId){
		
		LinkedHashMap<String, Object> infoMap = new LinkedHashMap<String, Object>();
		infoMap.put("resultCode", Constants.SUCCESS);
		infoMap.put("resultDesc", "成功");
		
		try{
			/*JSONObject obj = PeiniUtils.validToken(userId);
			if (obj.getInteger("resultCode") != 1) {
				return obj;
			}
			userId = obj.getString("userId");*/
			
			SellerJudgeExample judgeExample = new SellerJudgeExample();
			judgeExample.createCriteria().andOrderIdEqualTo(orderId);
			Integer cnt = sellerJudgeMapper.countByExample(judgeExample);
			OrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(orderId);
			if(orderInfo.getOrderType() == 1){
				sellerJudge.setTaskInfoId(orderInfo.getTaskInfoId());
			}
			
			sellerJudge.setCreateTime(new Date());
			//sellerJudge.setTaskInfoId(0);
			sellerJudge.setOrderId(orderId);
			// 计算总分数
			sellerJudge.setSellerScore((sellerJudge.getSellerServer()
					+ sellerJudge.getSellerCondition() + sellerJudge
					.getSellerMeal()) / 3);
			
			int result = insertJudge(sellerJudge);
			if (result > 0) {
				// 获取店铺评价总数
				SellerJudge sellerMap = selectBySellerId(sellerJudge.getSellerInfoId());
				// 计算评价分数
				SellerJudge sellerAll = new SellerJudge();
				sellerAll.setSellerInfoId(sellerJudge.getSellerInfoId());
				sellerAll.setSellerScore(sellerMap.getSellerScore()
						/ sellerMap.getNum());
				sellerAll.setSellerServer(sellerMap.getSellerServer()
						/ sellerMap.getNum());
				sellerAll.setSellerCondition(sellerMap.getSellerCondition()
						/ sellerMap.getNum());
				sellerAll.setSellerMeal(sellerMap.getSellerMeal()
						/ sellerMap.getNum());
				sellerInfoService.updateByJudge(sellerAll);
			}
	
			// 评价完成之后订单信息更新为已完成
			orderInfo.setOrderStatus(2);
			orderInfoMapper.updateByPrimaryKeySelective(orderInfo);
			
			OrderSellerExample sellerExample = new OrderSellerExample();
			sellerExample.createCriteria().andTaskIdEqualTo((long)orderInfo.getTaskInfoId()).andOrderTypeEqualTo(orderInfo.getOrderType()).andSellerIdEqualTo((long)orderInfo.getSellerInfoId());
			List<OrderSeller> orderSellers = orderSellerMapper.selectByExample(sellerExample);
			if(orderSellers.size() >= 0){
				OrderSeller orderSeller = orderSellers.get(0);
				orderSeller.setOrderStatus(2);
				orderSellerMapper.updateByPrimaryKey(orderSeller);
				
				SmsSendUtil.sendSmsNotify(orderSeller.getSellerId().toString(), orderSeller.getId().toString(), 23, "您的订单(订单号<a href='seller/orderDetail?orderId="+orderSeller.getId()+"'>"+orderSeller.getOrderCode()+"</a>)对方已评价");
				
				 //消息推送
				SellerInfo sellerinfo=sellerInfoService.selectById(Integer.parseInt(orderSeller.getSellerId().toString()));
				JSONObject object = new JSONObject();
		        object.put("title", "评价成功通知");
		        object.put("content", "您对\""+sellerinfo.getSellerName()+"\"店铺评价已收到，感谢您的惠顾~");
		        object.put("paramId", orderInfo.getId()+","+sellerinfo.getId());
		        object.put("type", 102);
		        object.put("paramId", orderInfo.getId()+","+sellerinfo.getId());
		        UserInfo newuserInfo = userInfoMapper.selectByPrimaryKey(userId);
				AppPush.sendPush(object,newuserInfo.getUserPhone().split(","));
				
				 //给发起人推送消息
		        
				SmsSendUtil.sendSmsNotify(userId, orderInfo.getId()+","+sellerinfo.getId(), 102, "您对\""+sellerinfo.getSellerName()+"\"店铺评价已收到，感谢您的惠顾~");
			}
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
		return infoMap;
	}
	
	
	public SellerJudge selectBySellerId(Integer id){
		SellerJudge sellerJudge = sellerJudgeMapper.selectBySellerId(id);
		return sellerJudge;
	}

	public Object sellerAndUserJudge(SellerJudge sellerJudge, UserJudge userJudge, Integer taskId, Long orderId){
		try {
			sellerJudge.setTaskInfoId(taskId);
			userJudge.setTaskInfoId(taskId);
			
			TaskInfo taskInfo = taskInfoMapper.selectByPrimaryKey(taskId);
			String userId = userJudge.getUserId();
			
			// 计算总分数
			sellerJudge.setSellerScore((sellerJudge.getSellerServer()
					+ sellerJudge.getSellerCondition() + sellerJudge
					.getSellerMeal()) / 3);
			// 店铺评价
			int result = insertJudge(sellerJudge);
			if (result > 0) {
				// 获取店铺评价总数
				SellerJudge sellerMap = selectBySellerId(sellerJudge.getSellerInfoId());
				// 计算评价分数
				SellerJudge sellerAll = new SellerJudge();
				sellerAll.setSellerInfoId(sellerJudge.getSellerInfoId());
				sellerAll.setSellerScore(sellerMap.getSellerScore()
						/ sellerMap.getNum());
				sellerAll.setSellerServer(sellerMap.getSellerServer()
						/ sellerMap.getNum());
				sellerAll.setSellerCondition(sellerMap.getSellerCondition()
						/ sellerMap.getNum());
				sellerAll.setSellerMeal(sellerMap.getSellerMeal()
						/ sellerMap.getNum());
				sellerInfoService.updateByJudge(sellerAll);
			}
	
			// 计算总分数
			userJudge.setUserScore((userJudge.getUserLife()
					+ userJudge.getUserImage() + userJudge.getUserDate()) / 3);
			// 用户评价
			int resultUser = userJudgeService.insertJudge(userJudge);
			String sore = "0";
			if (resultUser > 0) {
				// 获取用户评价总数
				UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userJudge.getOtherUserId());
				int taskNum = 0;
				if (userJudge.getUserScore() == 100) {
					taskNum = userInfoService.getTaskNum(userJudge.getOtherUserId(), +3);
					sore = "+3";
				} else if (userJudge.getUserScore() >= 80
						& userJudge.getUserScore() < 100) {
					taskNum = userInfoService.getTaskNum(userJudge.getOtherUserId(), +2);
					sore = "+2";
				} else if (userJudge.getUserScore() >= 60
						& userJudge.getUserScore() < 80) {
					taskNum = userInfoService.getTaskNum(userJudge.getOtherUserId(), +1);
					sore = "+1";
				} else if (userJudge.getUserScore() >= 20
						& userJudge.getUserScore() < 40) {
					taskNum = userInfoService.getTaskNum(userJudge.getOtherUserId(), -1);
					sore = "-1";
				} else if (userJudge.getUserScore() < 20) {
					taskNum = userInfoService.getTaskNum(userJudge.getOtherUserId(), -2);
					sore = "-2";
				}
				userInfo.setTaskNum(taskNum);
				userInfo.setReputation(PeiniUtils.getCredit(userInfo,1));
				
				UserJudge userMap = userJudgeService.selectByUserId(userJudge
						.getOtherUserId());
				// 计算评价分数
				userInfo.setUserScore(userMap.getUserScore() / userMap.getNum());
				userInfo.setUserLife(userMap.getUserLife() / userMap.getNum());
				userInfo.setUserImage(userMap.getUserImage() / userMap.getNum());
				userInfo.setUserDate(userMap.getUserDate() / userMap.getNum());
				//userInfoService.updateByUserJudge(userAll);
				userInfoMapper.updateByPrimaryKey(userInfo);
				
				SmsSendUtil.sendSmsNotify(userJudge.getOtherUserId(), taskInfo.getId().toString(), 6, "您的任务已完成"+sore+"分");
			}
	
			// 评价完成之后订单信息更新为已完成
			OrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(orderId);
			orderInfo.setOrderStatus(2);
			orderInfoService.updateOrderStatusByOrderId(orderInfo);
			
			OrderSellerExample example = new OrderSellerExample();
			example.createCriteria().andTaskIdEqualTo((long)taskId).andSellerIdEqualTo((long)sellerJudge.getSellerInfoId()).andOrderTypeEqualTo(1);
			List<OrderSeller> orderSellerList = orderSellerMapper.selectByExampleWithBLOBs(example);
			for (OrderSeller orderSeller : orderSellerList) {
				orderSeller.setOrderStatus(2);
				orderSellerMapper.updateByPrimaryKeySelective(orderSeller);
			}
			
			SellerInfo sellerMap=sellerInfoService.selectById(sellerJudge.getSellerInfoId());
			
	        //消息推送
			JSONObject object = new JSONObject();
	        object.put("title", "任务评价通知");
	        object.put("content", "您参与的“"+sellerMap.getSellerName()+"”任务已评价成功！快去参加下一轮任务吧~");
	        object.put("type", 107);
	        object.put("paramId", taskId.toString());
	        UserInfo newuserInfo = userInfoMapper.selectByPrimaryKey(userId);
			AppPush.sendPush(object,newuserInfo.getUserPhone().split(","));
			if (Integer.parseInt(sore)>0) {
				object.put("content", "您参与的“"+sellerMap.getSellerName()+"”任务对方已完成评价！恭喜您获得任务经验"+sore+"分~");
			}else {
				object.put("content", "您参与的“"+sellerMap.getSellerName()+"”任务对方已完成评价！由于对方给您的评价过低任务经验"+sore+"分~");
			}
			UserInfo userInfo = userInfoMapper.selectByPrimaryKey(taskInfo.getOtherUserId());
			AppPush.sendPush(object,userInfo.getUserPhone().split(","));
			
	        //给发起人推送消息
			SmsSendUtil.sendSmsNotify(userId, taskId.toString(), 107, "您参与的“"+sellerMap.getSellerName()+"”任务已评价成功！快去参加下一轮任务吧~");
			
			String content = "";
			if (Integer.parseInt(sore)>0) {
				content = "您参与的“"+sellerMap.getSellerName()+"”任务对方已完成评价！恭喜您获得任务经验"+sore+"分~";
			}else {
				content = "您参与的“"+sellerMap.getSellerName()+"”任务对方已完成评价！由于对方给您的评价过低任务经验"+sore+"分~";
			}
			SmsSendUtil.sendSmsNotify(taskInfo.getOtherUserId(), taskId.toString(), 107, content);
			
			if(taskInfo.getUserId().equals(userId)){//发布者评价
				taskInfo.setTaskStatus(4);
			}else{//参与者评价
				taskInfo.setTaskOtherStatus(41);
			}
			taskInfoMapper.updateByPrimaryKeySelective(taskInfo);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
		return null;
	}
}
